<template>
  <div class="teacher-management">
    <h1 class="page-title">教师管理</h1>
    
    <div class="action-bar">
      <div class="search-box">
        <el-input
          v-model="searchQuery"
          placeholder="搜索教师姓名"
          prefix-icon="el-icon-search"
          clearable
          @clear="fetchTeachers"
          @keyup.enter="searchTeachers"
        ></el-input>
        <el-button type="primary" @click="searchTeachers">搜索</el-button>
      </div>
      
      <div class="action-buttons">
        <el-button type="success" @click="showAddTeacherDialog">添加教师</el-button>
        <el-button type="warning" @click="resetSelectedPasswords" :disabled="!hasSelection">重置密码</el-button>
        <el-button type="danger" @click="showDeleteConfirm" :disabled="!hasSelection">批量删除</el-button>
      </div>
    </div>
    
    <div class="table-container">
      <el-table
        :data="teachers"
        border
        stripe
        @selection-change="handleSelectionChange"
        v-loading="loading"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="teacherId" label="教师工号" width="120"></el-table-column>
        <el-table-column prop="name" label="姓名" width="120"></el-table-column>
        <el-table-column prop="subject" label="学科" width="120"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="phone" label="电话"></el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '正常' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="lastLoginTime" label="最近登录时间" width="180"></el-table-column>
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="scope">
            <div class="operation-buttons">
              <el-button type="primary" size="small" @click="editTeacher(scope.row)">编辑</el-button>
              <el-button type="warning" size="small" @click="resetPassword(scope.row)">重置密码</el-button>
              <el-button 
                type="danger" 
                size="small" 
                @click="deleteTeacher(scope.row.id)"
              >删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    
    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>
    
    <!-- 添加/编辑教师对话框 -->
    <el-dialog
      :title="dialogType === 'add' ? '添加教师' : '编辑教师'"
      v-model="dialogVisible"
      width="500px"
    >
      <el-form :model="teacherForm" :rules="rules" ref="teacherFormRef" label-width="100px">
        <el-form-item label="教师工号" prop="teacherId">
          <el-input v-model="teacherForm.teacherId" placeholder="系统自动生成" disabled v-if="dialogType === 'edit'"></el-input>
          <el-input v-model="teacherForm.teacherId" placeholder="留空则自动生成" v-else></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="teacherForm.name" placeholder="请输入教师姓名"></el-input>
        </el-form-item>
        <el-form-item label="学科" prop="subject">
          <el-select v-model="teacherForm.subject" placeholder="请选择学科" style="width: 100%;">
            <el-option label="语文" value="chinese"></el-option>
            <el-option label="数学" value="math"></el-option>
            <el-option label="英语" value="english"></el-option>
            <el-option label="物理" value="physics"></el-option>
            <el-option label="化学" value="chemistry"></el-option>
            <el-option label="生物" value="biology"></el-option>
            <el-option label="历史" value="history"></el-option>
            <el-option label="地理" value="geography"></el-option>
            <el-option label="政治" value="politics"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="teacherForm.email" placeholder="请输入邮箱"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="teacherForm.phone" placeholder="请输入电话号码"></el-input>
        </el-form-item>
        <el-form-item label="初始密码" prop="password" v-if="dialogType === 'add'">
          <el-input v-model="teacherForm.password" placeholder="不填则使用默认密码" show-password></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitTeacherForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 重置密码对话框 -->
    <el-dialog
      title="重置密码"
      v-model="resetDialogVisible"
      width="500px"
    >
      <p>您确定要重置以下教师的密码吗？</p>
      <p v-if="selectedTeachers.length === 1">教师: {{ selectedTeachers[0].name }} ({{ selectedTeachers[0].teacherId }})</p>
      <p v-else>已选择 {{ selectedTeachers.length }} 名教师</p>
      
      <el-form :model="resetForm" :rules="resetRules" ref="resetFormRef" label-width="100px">
        <el-form-item label="新密码" prop="password">
          <el-input v-model="resetForm.password" placeholder="不填则使用默认密码" show-password></el-input>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="resetDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmResetPasswords">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, reactive, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import axios from 'axios';

// 教师列表数据
const teachers = ref([]);
const loading = ref(false);
const searchQuery = ref('');
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const selectedTeachers = ref([]);
const hasSelection = computed(() => selectedTeachers.value.length > 0);

// 表单相关
const dialogVisible = ref(false);
const dialogType = ref('add'); // 'add' 或 'edit'
const teacherFormRef = ref(null);
const teacherForm = reactive({
  id: null,
  teacherId: '',
  name: '',
  gender: 1,
  email: '',
  phone: '',
  subject: '',
  status: 1,
  password: ''
});

const rules = {
  name: [
    { required: true, message: '请输入教师姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  subject: [
    { required: true, message: '请选择学科', trigger: 'change' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
};

// 重置密码相关
const resetDialogVisible = ref(false);
const resetFormRef = ref(null);
const resetForm = reactive({
  password: ''
});

const resetRules = {
  password: [
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ]
};

// 监听分页变化
watch([currentPage, pageSize], () => {
  fetchTeachers();
});

// 获取教师列表
const fetchTeachers = async () => {
  loading.value = true;
  try {
    const response = await axios.get('/api/admin/teachers', {
      params: {
        page: currentPage.value,
        size: pageSize.value,
        query: searchQuery.value
      }
    });
    
    if (response.data && response.data.success) {
      // 检查响应格式，支持两种可能的数据结构
      if (response.data.data.records) {
        // 新格式 - 带有分页信息的记录
        teachers.value = response.data.data.records;
        total.value = response.data.data.total;
      } else {
        // 旧格式 - 直接返回教师列表和单独的分页信息
        teachers.value = response.data.data;
        total.value = response.data.total || response.data.data.length;
      }
    } else {
      ElMessage.error(response.data.message || '获取教师列表失败');
    }
  } catch (error) {
    console.error('获取教师列表错误:', error);
    ElMessage.error('获取教师列表失败，请检查网络连接');
  } finally {
    loading.value = false;
  }
};

// 搜索教师
const searchTeachers = () => {
  currentPage.value = 1;
  fetchTeachers();
};

// 添加教师对话框
const showAddTeacherDialog = () => {
  dialogType.value = 'add';
  Object.keys(teacherForm).forEach(key => {
    if (key !== 'gender' && key !== 'status') {
      teacherForm[key] = '';
    }
  });
  teacherForm.gender = 1;
  teacherForm.status = 1;
  dialogVisible.value = true;
};

// 编辑教师
const editTeacher = (row) => {
  dialogType.value = 'edit';
  Object.keys(teacherForm).forEach(key => {
    if (key in row) {
      teacherForm[key] = row[key];
    }
  });
  dialogVisible.value = true;
};

// 提交教师表单
const submitTeacherForm = async () => {
  if (!teacherFormRef.value) return;
  
  await teacherFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 创建一个新的对象，不包含lastLoginTime字段
        const teacherData = { ...teacherForm };
        delete teacherData.lastLoginTime;
        
        if (dialogType.value === 'add') {
          // 添加教师
          const response = await axios.post('/api/admin/teacher', teacherData);
          if (response.data && response.data.success) {
            ElMessage.success('添加教师成功');
            dialogVisible.value = false;
            fetchTeachers();
          } else {
            ElMessage.error(response.data.message || '添加教师失败');
          }
        } else {
          // 更新教师
          const response = await axios.put(`/api/admin/teacher/${teacherData.id}`, teacherData);
          if (response.data && response.data.success) {
            ElMessage.success('更新教师信息成功');
            dialogVisible.value = false;
            fetchTeachers();
          } else {
            ElMessage.error(response.data.message || '更新教师信息失败');
          }
        }
      } catch (error) {
        console.error('提交教师表单错误:', error);
        ElMessage.error(error.response?.data?.message || '操作失败，请稍后重试');
      }
    } else {
      return false;
    }
  });
};

// 删除教师
const deleteTeacher = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除该教师吗？此操作不可逆', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    
    const response = await axios.delete(`/api/admin/teacher/${id}`);
    if (response.data && response.data.success) {
      ElMessage.success('删除教师成功');
      fetchTeachers();
    } else {
      ElMessage.error(response.data.message || '删除教师失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除教师错误:', error);
      ElMessage.error(error.response?.data?.message || '操作失败，请稍后重试');
    }
  }
};

// 重置密码
const resetPassword = (teacher) => {
  selectedTeachers.value = [teacher];
  resetForm.password = '';
  resetDialogVisible.value = true;
};

// 批量重置密码
const resetSelectedPasswords = () => {
  if (selectedTeachers.value.length === 0) {
    ElMessage.warning('请选择需要重置密码的教师');
    return;
  }
  
  resetForm.password = '';
  resetDialogVisible.value = true;
};

// 确认重置密码
const confirmResetPasswords = async () => {
  try {
    const teacherIds = selectedTeachers.value.map(t => t.id);
    const response = await axios.post('/api/admin/teachers/reset-password', {
      teacherIds,
      password: resetForm.password || undefined // 如果为空则使用默认密码
    });
    
    if (response.data && response.data.success) {
      ElMessage.success('密码重置成功');
      resetDialogVisible.value = false;
    } else {
      ElMessage.error(response.data.message || '密码重置失败');
    }
  } catch (error) {
    console.error('重置密码错误:', error);
    ElMessage.error(error.response?.data?.message || '操作失败，请稍后重试');
  }
};

// 表格选择变化
const handleSelectionChange = (selection) => {
  selectedTeachers.value = selection;
};

// 批量删除确认
const showDeleteConfirm = async () => {
  if (selectedTeachers.value.length === 0) {
    ElMessage.warning('请选择需要删除的教师');
    return;
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedTeachers.value.length} 名教师吗？此操作不可逆`,
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );
    
    const teacherIds = selectedTeachers.value.map(t => t.id);
    const response = await axios.post('/api/admin/teachers/batch-delete', { teacherIds });
    
    if (response.data && response.data.success) {
      ElMessage.success('批量删除成功');
      fetchTeachers();
    } else {
      ElMessage.error(response.data.message || '批量删除失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除错误:', error);
      ElMessage.error(error.response?.data?.message || '操作失败，请稍后重试');
    }
  }
};

// 初始化
onMounted(() => {
  fetchTeachers();
});
</script>

<style scoped>
.teacher-management {
  padding: 20px;
  position: relative;
  z-index: 1;
  overflow-x: hidden;
  width: 100%;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  margin-bottom: 24px;
  color: #333;
}

.action-bar {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
  align-items: center;
}

.search-box {
  display: flex;
  gap: 10px;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

.table-container {
  width: 100%;
  overflow-x: auto;
  margin-bottom: 20px;
  position: relative;
  z-index: 2;
}

:deep(.el-table) {
  width: 100% !important;
  min-width: 1000px !important;
}

:deep(.el-table__body-wrapper) {
  overflow-x: auto !important;
}

.operation-buttons {
  display: flex;
  flex-direction: row;
  gap: 5px;
  justify-content: flex-start;
}

/* 修改操作按钮样式，使其更紧凑 */
.operation-buttons .el-button {
  margin: 0;
  padding: 6px 12px;
  min-width: 60px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style> 